#coding=utf-8
import datetime
import json

import itchat
import random
from collections import deque
import time
import re

import requests

history = deque([], 100)   #这个是百人队列，支持先后顺序的，很厉害
author=''
author1=''
fanli1 = re.compile(r'20[0-9]{0,2}\.[0-9]{0,2}Z')
fanli2 = re.compile(r'[0-9]{0,2}\.[0-9]{0,2}')
fanli3= re.compile('没有推广亲')
getshoppingname=re.compile(r'[\u3010](.{0,100})[\u3011]')
UserId=''
nofind = '没有推广亲'

try:
    itchat.auto_login(hotReload=True)
except:
    itchat.auto_login()



#########################################################

# 调用tkl_get_gaoyong(客户发来的淘口令)   取得高佣信息

# 例子
# tkl_get_gaoyong('￥g3QubyXpBOV￥')  # 无券有佣金

# tkl_get_gaoyong('￥Y4hQbyXpMDs￥')  #有券有佣金

#########################################################



#喵口令api请求构造
class config():
    # pid（mm_账号id_推广渠道id_推广位id）
    # mm_memberId_siteId_adzoneId
    # mm_28964573_303450418_82851750421
    pid = 'mm_28964573_303450418_82851750421'  # 淘宝联盟密令 '6e39417a-bc77-3d4d-c2ae-0a51f37d2574'   # 喵口令密令
    apkey = '6e39417a-bc77-3d4d-c2ae-0a51f37d2574'  # 喵口令密令
    tbname = 'shenhuawade'
    tpwdcode = '￥OxXGby1GRvh￥'  #任意淘口令
    tpwd='1'    #是否生成淘口令，1为生成，不填则不生成
    shorturl='1'    #是否需要短链接，1为生成，不填则不生成
    extsearch ='1'  #官方查不到券时是否去第三方平台查询，1为启用
    tpwdpic=''  #商品图片链接，用于打开口令时显示，不填写默认为商品主图
    piddict = {'刘雯雯vip':'mm_28964573_314650248_85913900435'
        , "pid001": "mm_28964573_26464518_108345900099"
        , "pid002": "mm_28964573_26464518_108345350188"
        , "pid003": "mm_28964573_26464518_108345550146"
        , "pid004": "mm_28964573_26464518_108346150049"
        , "pid005": "mm_28964573_26464518_108346250014"
        , "pid006": "mm_28964573_26464518_108345800108"
        , "pid007": "mm_28964573_26464518_108345150209"
        , "pid008": "mm_28964573_26464518_108345150210"
        , "pid009": "mm_28964573_26464518_108345500153"
        , "pid010": "mm_28964573_26464518_108345950092"
        , "pid011": "mm_28964573_26464518_108344000499"
        , "pid012": "mm_28964573_26464518_108346350001"
        , "pid013": "mm_28964573_26464518_108345700149"
        , "pid014": "mm_28964573_26464518_108344350374"
        , "pid015": "mm_28964573_26464518_108346300016"
        , "pid016": "mm_28964573_26464518_108344900261"
        , "pid017": "mm_28964573_26464518_108345200198"
        , "pid018": "mm_28964573_26464518_108344400406"
        , "pid019": "mm_28964573_26464518_108346000095"
        , "pid020": "mm_28964573_26464518_108344750279"
        , "pid021": "mm_28964573_26464518_108344300429"
        , "pid022": "mm_28964573_26464518_108345400176"
        , "pid023": "mm_28964573_26464518_108343850491"
        , "pid024": "mm_28964573_26464518_108345050216"
        , "pid025": "mm_28964573_26464518_108346300022"
        , "pid026": "mm_28964573_26464518_108343850494"
        , "pid027": "mm_28964573_26464518_108344850232"
        , "pid028": "mm_28964573_26464518_108345350205"
        , "pid029": "mm_28964573_26464518_108344950261"
        , "pid030": "mm_28964573_26464518_108346350002"
        , "pid031": "mm_28964573_26464518_108344700273"
        , "pid032": "mm_28964573_26464518_108344450390"
        , "pid033": "mm_28964573_26464518_108345600181"
        , "pid034": "mm_28964573_26464518_108343850500"
        , "pid035": "mm_28964573_26464518_108344100430"
        , "pid036": "mm_28964573_26464518_108346100067"
        , "pid037": "mm_28964573_26464518_108344900267"
        , "pid038": "mm_28964573_26464518_108345100216"
        , "pid039": "mm_28964573_26464518_108345700155"
        , "pid040": "mm_28964573_26464518_108344500371"
        , "pid041": "mm_28964573_26464518_108344250411"
        , "pid042": "mm_28964573_26464518_108344200424"
        , "pid043": "mm_28964573_26464518_108346250023"
        , "pid044": "mm_28964573_26464518_108345050227"
        , "pid045": "mm_28964573_26464518_108346350007"
        , "pid046": "mm_28964573_26464518_108344300440"
        , "pid047": "mm_28964573_26464518_108345700161"
        , "pid048": "mm_28964573_26464518_108344200427"
        , "pid049": "mm_28964573_26464518_108345750138"
        , "pid050": "mm_28964573_26464518_108345250207"
        , "pid051": "mm_28964573_26464518_108345550159"
        , "pid052": "mm_28964573_26464518_108345150234"
        , "pid053": "mm_28964573_26464518_108346050091"
        , "pid054": "mm_28964573_26464518_108345750142"
        , "pid055": "mm_28964573_26464518_108346400010"
        , "pid056": "mm_28964573_26464518_108345750143"
        , "pid057": "mm_28964573_26464518_108345900118"
        , "pid058": "mm_28964573_26464518_108344550329"
        , "pid059": "mm_28964573_26464518_108346250033"
        , "pid060": "mm_28964573_26464518_108345100224"
        , "pid061": "mm_28964573_26464518_108345550161"
        , "pid062": "mm_28964573_26464518_108345450195"
        , "pid063": "mm_28964573_26464518_108344450403"
        , "pid064": "mm_28964573_26464518_108344550330"
        , "pid065": "mm_28964573_26464518_108346050095"
        , "pid066": "mm_28964573_26464518_108344050492"
        , "pid067": "mm_28964573_26464518_108345850117"
        , "pid068": "mm_28964573_26464518_108346350018"
        , "pid069": "mm_28964573_26464518_108345950117"
        , "pid070": "mm_28964573_26464518_108344750302"
        , "pid071": "mm_28964573_26464518_108345750148"
        , "pid072": "mm_28964573_26464518_108344100440"
        , "pid073": "mm_28964573_26464518_108344100441"
        , "pid074": "mm_28964573_26464518_108344350387"
        , "pid075": "mm_28964573_26464518_108345150240"
        , "pid076": "mm_28964573_26464518_108345000238"
        , "pid077": "mm_28964573_26464518_108344900283"
        , "pid078": "mm_28964573_26464518_108344400428"
        , "pid079": "mm_28964573_26464518_108344100442"
        , "pid080": "mm_28964573_26464518_108345100228"
        , "pid081": "mm_28964573_26464518_108345200219"
        , "pid082": "mm_28964573_26464518_108345050235"
        , "pid083": "mm_28964573_26464518_108344300450"
        , "pid084": "mm_28964573_26464518_108345700168"
        , "pid085": "mm_28964573_26464518_108345850119"
        , "pid086": "mm_28964573_26464518_108344900285"
        , "pid087": "mm_28964573_26464518_108344150473"
        , "pid088": "mm_28964573_26464518_108344700284"
        , "pid089": "mm_28964573_26464518_108346100087"
        , "pid090": "mm_28964573_26464518_108344250423"
        , "pid091": "mm_28964573_26464518_108344900287"
        , "pid092": "mm_28964573_26464518_108345750150"
        , "pid093": "mm_28964573_26464518_108345900126"
        , "pid094": "mm_28964573_26464518_108346400029"
        , "pid095": "mm_28964573_26464518_108344300455"
        , "pid096": "mm_28964573_26464518_108346100089"
        , "pid097": "mm_28964573_26464518_108344850249"
        , "pid098": "mm_28964573_26464518_108346050110"
        , "pid099": "mm_28964573_26464518_108345100234"
        , "pid100": "mm_28964573_26464518_108344550338"
        , "pid101": "mm_28964573_26464518_108344250425"
        , "pid102": "mm_28964573_26464518_108346050111"
        , "pid103": "mm_28964573_26464518_108345700172"
        , "pid104": "mm_28964573_26464518_108345600203"
        , "pid105": "mm_28964573_26464518_108345800147"
        , "pid106": "mm_28964573_26464518_108344500388"
        , "pid107": "mm_28964573_26464518_108345900133"
        , "pid108": "mm_28964573_26464518_108346250045"
        , "pid109": "mm_28964573_26464518_108345950128"
        , "pid110": "mm_28964573_26464518_108345550167"
        , "pid111": "mm_28964573_26464518_108346050113"
        , "pid112": "mm_28964573_26464518_108345800149"
        , "pid113": "mm_28964573_26464518_108345400206"
        , "pid114": "mm_28964573_26464518_108345200229"
        , "pid115": "mm_28964573_26464518_108345650172"
        , "pid116": "mm_28964573_26464518_108345200231"
        , "pid117": "mm_28964573_26464518_108345300192"
        , "pid118": "mm_28964573_26464518_108346300054"
        , "pid119": "mm_28964573_26464518_108345750160"
        , "pid120": "mm_28964573_26464518_108344350394"
        , "pid121": "mm_28964573_26464518_108346150075"
        , "pid122": "mm_28964573_26464518_108345300194"
        , "pid123": "mm_28964573_26464518_108344450418"
        , "pid124": "mm_28964573_26464518_108346350034"
        , "pid125": "mm_28964573_26464518_108345800151"
        , "pid126": "mm_28964573_26464518_108344600373"
        , "pid127": "mm_28964573_26464518_108344750314"
        , "pid128": "mm_28964573_26464518_108345900135"
        , "pid129": "mm_28964573_26464518_108346300056"
        , "pid130": "mm_28964573_26464518_108345800152"
        , "pid131": "mm_28964573_26464518_108344850258"
        , "pid132": "mm_28964573_26464518_108346450008"
        , "pid133": "mm_28964573_26464518_108345600210"
        , "pid134": "mm_28964573_26464518_108344450419"
        , "pid135": "mm_28964573_26464518_108344400443"
        , "pid136": "mm_28964573_26464518_108344100458"
        , "pid137": "mm_28964573_26464518_108346200091"
        , "pid138": "mm_28964573_26464518_108345750166"
        , "pid139": "mm_28964573_26464518_108346200093"
        , "pid140": "mm_28964573_26464518_108345800154"
        , "pid141": "mm_28964573_26464518_108344100459"
        , "pid142": "mm_28964573_26464518_108344600378"
        , "pid143": "mm_28964573_26464518_108346000132"
        , "pid144": "mm_28964573_26464518_108345350236"
        , "pid145": "mm_28964573_26464518_108346050126"
        , "pid146": "mm_28964573_26464518_108345850134"
        , "pid147": "mm_28964573_26464518_108344550348"
        , "pid148": "mm_28964573_26464518_108344350398"
        , "pid149": "mm_28964573_26464518_108345000255"
        , "pid150": "mm_28964573_26464518_108346350041"
        , "pid151": "mm_28964573_26464518_108345600215"
        , "pid152": "mm_28964573_26464518_108344100462"
        , "pid153": "mm_28964573_26464518_108345750170"
        , "pid154": "mm_28964573_26464518_108345000257"
        , "pid155": "mm_28964573_26464518_108345350240"
        , "pid156": "mm_28964573_26464518_108345500196"
        , "pid157": "mm_28964573_26464518_108344700297"
        , "pid158": "mm_28964573_26464518_108344900302"
        , "pid159": "mm_28964573_26464518_108345300203"
        , "pid160": "mm_28964573_26464518_108345650186"
        , "pid161": "mm_28964573_26464518_108344100463"
        , "pid162": "mm_28964573_26464518_108344850268"
        , "pid163": "mm_28964573_26464518_108344400456"
        , "pid164": "mm_28964573_26464518_108346200099"
        , "pid165": "mm_28964573_26464518_108344550350"
        , "pid166": "mm_28964573_26464518_108346250056"
        , "pid167": "mm_28964573_26464518_108344550351"
        , "pid168": "mm_28964573_26464518_108345900143"
        , "pid169": "mm_28964573_26464518_108344650356"
        , "pid170": "mm_28964573_26464518_108344200446"
        , "pid171": "mm_28964573_26464518_108344550352"
        , "pid172": "mm_28964573_26464518_108344800277"
        , "pid173": "mm_28964573_26464518_108344850269"
        , "pid174": "mm_28964573_26464518_108346100108"
        , "pid175": "mm_28964573_26464518_108344700300"
        , "pid176": "mm_28964573_26464518_108345800159"
        , "pid177": "mm_28964573_26464518_108344500403"
        , "pid178": "mm_28964573_26464518_108346000138"
        , "pid179": "mm_28964573_26464518_108344800282"
        , "pid180": "mm_28964573_26464518_108345000267"

               }

#淘口令返回值构造
class backtkl():
    """
    {商品名称 item_name}，{商品原价 item_price}，{二合一口令 item_tkl}，{券价格 item_youhuiquan}，{券后价格 item_quanhouprice}，{二合一短链 tiem_2and1_url}，{佣金 item_fanli}，{二合一原链}，{同款推荐}
    """
    item_name = ''
    item_price = ''
    item_tkl = ''
    item_youhuiquan = ''
    item_quanhouprice = ''
    item_2and1_url = ''
    item_fanli = 0
    #返佣比例
    item_fanbili=0.01
    #淘宝技术服务费用
    item_alifuwu = 10
    #淘宝住技术服务费
    item_tbzhufw = 10

# 喵口令api—任意淘口令转高佣,构造返回dict完整参数,（淘口令，通过备注名字查找pid字典表格）
def tkl_get_gaoyong(tkl,RemarkName):


    try:
        tkjdurl = ('https://api.open.21ds.cn/apiv1/getitemgyurlbytpwd?apkey=%s&tpwdcode=%s&pid=%s&tbname=%s&tpwd=%s&shorturl=%s&extsearch=%s&tpwdpic=%s' % (
            config.apkey, tkl, config.piddict[RemarkName], config.tbname, config.tpwd,config.shorturl,config.extsearch,config.tpwdpic))
        print("vip用户"+RemarkName+"发送查询使用的pid值为"+config.piddict[RemarkName])
        # print(tkjdurl)
        resp = requests.get(tkjdurl)
        content = resp.content
        #byte转化成dict
        content = json.loads(content)
        # print(content)
        # 找不到券/请求失败统一用nofind该参数
        nofind = '没有推广亲'

        if content['code'] == -1:
            if content['data'] == '该item_id对应宝贝已下架或非淘客宝贝':
                print('该item_id对应宝贝已下架或非淘客宝贝')
                return nofind
            else:
                print('tkl_get_gaoyong函数出现请求错误，错误代码%s ，错误原因：%s' % (content['code'], content['msg']))
                return nofind
        elif content['code'] == 401:
            print('tkl_get_gaoyong函数出现请求错误，错误代码%s ，错误原因：%s' %(content['code'],content))
            return nofind
        elif content['code'] == 429:
            print('tkl_get_gaoyong函数出现请求错误，错误代码%s ，错误原因：%s' %(content['code'],content))
            return nofind
        elif content['code'] == 403:
            print('tkl_get_gaoyong函数出现请求错误，错误代码%s ，错误原因：%s' %(content['code'],content))
            return nofind
        elif content['code'] == 405:
            print('请求方式不对')
            print('tkl_get_gaoyong函数出现请求错误，错误代码%s ，错误原因：%s' %(content['code'],content))
            return nofind

        elif content['code'] == 200:
            # 获取itemid
            itemid = content['result']['data']['item_id']
            # 获取item淘宝客商品信息dict
            iteminfo = get_tbk_item_info(itemid)

            #商品标题
            backtkl.item_name  = iteminfo['data']['n_tbk_item']['title']
            #商品价格
            backtkl.item_price = iteminfo['data']['n_tbk_item']['zk_final_price']
            #商品淘口令
            backtkl.item_tkl = content['result']['data']['tpwd']

            #返佣金比例
            backtkl.item_fanbili = content['result']['data']['max_commission_rate']

            itemname = iteminfo['data']['n_tbk_item']['title']

            #item_2and1_url 二合一url
            backtkl.item_2and1_url = content['result']['data']['short_url']
            # print(backtkl.item_2and1_url)
            # 检查该商品是否有券 has_coupon
            has_coupon = content['result']['data']['has_coupon']
            if has_coupon:
                #有券有佣金
                # 商品优惠券面额
                backtkl.item_youhuiquan = content['result']['data']['youhuiquan']

                #商品优惠后价格
                backtkl.item_quanhouprice = float(backtkl.item_price)-float(backtkl.item_youhuiquan)

                #计算有券佣金,并保留两位小数  （券后价格*佣金比例 = 佣金金额）高佣max_commission_rate  技术服务费10%：backtkl.item_alifuwu
                backtkl.item_fanli ='%.2f' % (float(backtkl.item_quanhouprice)*float(backtkl.item_fanbili)/100*0.9)

                print(backtkl.__dict__)

                print('佣金为:',backtkl.item_fanli)
                return backtkl


            else:
                #无券有佣金
                #------初始化数据-------#
                backtkl.item_youhuiquan = ''
                backtkl.item_quanhouprice = ''
                backtkl.item_fanli = 0
                print('meiyou')
                #计算无券佣金,并保留两位小数  （商品原价格*佣金比例 = 佣金金额）高佣max_commission_rate  技术服务费10%：backtkl.item_alifuwu
                backtkl.item_fanli ='%.2f' % (float(backtkl.item_price)*float(backtkl.item_fanbili)/100*0.9)

                print(backtkl.__dict__)
                print('佣金为:',backtkl.item_fanli)
                return backtkl
        else:
            print (tkjdurl+"tkl_get_gaoyong系统错误，请检查匹配错误码问题")
            return backtkl
    except:
        print("获取淘口令基础性请求失败,if else代码错误,可能是喵口令白名单限制了")
        # return '获取淘口令基础性请求失败,if else代码错误,可能是喵口令白名单限制了'
        return backtkl

#根据itemid 获取简版淘宝商品信息，获取淘宝完整dic参数
def get_tbk_item_info(itemid):
    tkjdurl = (
                'https://api.open.21ds.cn/apiv1/getiteminfo?apkey=%s&itemid=%s' % (
        config.apkey, itemid))
    resp = requests.get(tkjdurl)
    content = resp.content
    content = json.loads(content)

    if content['code'] == -1:
        print('函数get_tbk_item_info出错' +content)

    elif content['code'] == 401:
        print('函数get_tbk_item_info出错' +content)


    elif content['code'] == 429:
        print('函数get_tbk_item_info出错' +content)


    elif content['code'] == 403:
        print('函数get_tbk_item_info出错' +content)

    elif content['code'] == 405:
        print('函数get_tbk_item_info出错' +content)


    elif content['code'] == 200:
        # print(content)
        return content
    else:
        print(tkjdurl + "函数get_tbk_item_info系统错误，请检查")


# tkl_get_gaoyong('￥g3QubyXpBOV￥')  # 无券有佣金
# #
# tkl_get_gaoyong('￥Y4hQbyXpMDs￥')  #有券有佣金



#正则匹配提取淘口令
def match_kl(msg):#\x{ffe5}([a-zA-Z0-9]{11})\x{ffe5}#isu
    tkl = re.compile(r'￥\S{11}￥')
    tkllist = re.findall(tkl, msg)
    if tkllist:
        return tkllist[0]
    #匹配xxx关键字
    elif msg=='xxx':
        answer_content = 'XXXXXX'
        # print(msg)
        return 'xxx'

def real_time():
    r_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return r_time
def real_hourtime():
    hourtime=datetime.datetime.now().strftime('%H')
    return hourtime
def tihuanneirong(text):
    print(re.sub(fanli1, '', text, 1))
    return re.sub(fanli1, '', text, 1)

#价格判断函数
def panduanduoshaoqian(money):
    # 生成随机数，浮点类型
    # a = random.uniform(0, 0.7)
    # 控制随机数的精度round(数值，精度)
    # mynum=round(a, 2)
    mynum1=0.3
    jiage =round((money * 0.3 + mynum1),2)
    jiage1 =round((money * 0.01),2)
    if money>=10:
        if jiage>15:
            ok=str(4+jiage1)
            good = "返现" +ok+ "元"
        else:
            good = "返现"+str(jiage)+"元"
    elif 5<=money<10:
        good="返现"+str(jiage)+"元"
    elif 2.5<=money<5:
        good = "返现2元"
    elif 1.5<=money< 2.5:
        good = "返现1元"
    elif 1<=money< 1.5:
        good="返现0.8元"
    elif 0.3<=money< 1:
        good="返现0.5元"
    elif 0.1<=money< 0.3:
        good="返现0.5元"
    else:
        good=""
    print(good)
    return good


# 获取日志信息log.txt
def getlog():
    try:
        itchat.send('尊敬的上帝，这是你想要的[太阳]', toUserName='filehelper')
        itchat.send_file('log.txt', toUserName='filehelper')
    except:
        pass


# 获取日志信息log.txt
def clearlog():
    try:
        f = open('log.txt', "r+")
        f.truncate()
        f.close()
        with open('log.txt', 'w',encoding='utf-8') as f:
            f.write('[新日志开始时间]'+real_time()+'\n')

    except:
        pass

#写入日志信息
def writetxt(str,username,usermsg):
    try:
        with open('log.txt', 'a',encoding='utf-8') as f:
            f.write('[日志时间]'+real_time()+'--'+username+'--消息内容'+str+'--'+usermsg+ '\n')
    except:
        pass

@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
    print(real_hourtime()+'\n')
    # print(msg)
    try:
        writetxt("接收消息",msg['User']['NickName'],msg['Text'])
    except:
        pass
    print("接收消息",msg['Text'])
    # print(msg,'1这是查寻人的代号')

    #update_friend  每次查询都要先更新好友信息
    itchat.get_friends(update=True)#现更新号上的字典，然后下一步查找想要发送的人

    list = ['刘雯雯vip',"pid001","pid002","pid003","pid004","pid005","pid006","pid007","pid008","pid009","pid010","pid011","pid012","pid013","pid014","pid015","pid016","pid017","pid018","pid019","pid020","pid021","pid022","pid023","pid024","pid025","pid026","pid027","pid028","pid029","pid030","pid031","pid032","pid033","pid034","pid035","pid036","pid037","pid038","pid039","pid040","pid041","pid042","pid043","pid044","pid045","pid046","pid047","pid048","pid049","pid050","pid051","pid052","pid053","pid054","pid055","pid056","pid057","pid058","pid059","pid060","pid061","pid062","pid063","pid064","pid065","pid066","pid067","pid068","pid069","pid070","pid071","pid072","pid073","pid074","pid075","pid076","pid077","pid078","pid079","pid080","pid081","pid082","pid083","pid084","pid085","pid086","pid087","pid088","pid089","pid090","pid091","pid092","pid093","pid094","pid095","pid096","pid097","pid098","pid099","pid100","pid101","pid102","pid103","pid104","pid105","pid106","pid107","pid108","pid109","pid110","pid111","pid112","pid113","pid114","pid115","pid116","pid117","pid118","pid119","pid120","pid121","pid122","pid123","pid124","pid125","pid126","pid127","pid128","pid129","pid130","pid131","pid132","pid133","pid134","pid135","pid136","pid137","pid138","pid139","pid140","pid141","pid142","pid143","pid144","pid145","pid146","pid147","pid148","pid149","pid150","pid151","pid152","pid153","pid154","pid155","pid156","pid157","pid158","pid159","pid160","pid161","pid162","pid163","pid164","pid165","pid166","pid167","pid168","pid169","pid170","pid171","pid172","pid173","pid174","pid175","pid176","pid177","pid178","pid179","pid180"]

    if msg['User']['RemarkName'] in list:   # 看发消息的备注是否在vip目录里
            # print(msg['User']['RemarkName'])
            # print(msg['User']['RemarkName'])
            # print(msg['User']['RemarkName'])
            # print(msg['User']['RemarkName'])
            # print(msg['User']['RemarkName'])
            writetxt("消息到vip消息---:",msg['User']['NickName'], '该商品没有推广')

            search_tkl = match_kl(msg['Text'])  #匹配淘口令
            if search_tkl:
                tkl =tkl_get_gaoyong(search_tkl,msg['User']['RemarkName'])   #（淘口令，高佣查询人的备注名）
                if tkl == nofind:
                    writetxt("vip无推广回复---:",msg['User']['NickName'],'该商品没有推广')
                    fageichaxunren('该商品没有推广',msg['FromUserName']) # 发送信息给XXXX人
                else:
                    if str(tkl.item_fanli)== '0':
                        writetxt("vip无推广回复---:",msg['User']['NickName'], '该商品没有推广')
                        fageichaxunren('该商品没有推广', msg['FromUserName'])  # 发送信息给XXXX人
                    else:
                        # print(str(tkl.item_fanli))
                        #    + '\n' +
                        if tkl.item_youhuiquan == '':
                            print('无券有佣金')
                            rebackmsg = '钻石用户【%s】 您好\n\n【%s】\n [口令]%s\n  该商品没有优惠券，买的话会有高佣哦\n[太阳][太阳]如果买了预计结算的[红包]大约为：%s 元\n' % \
                                        (msg['User']['NickName'], tkl.item_name, tkl.item_tkl, tkl.item_fanli)
                            # warning = '友好提醒---佣金默认为高级，查询的扣除10%的阿里服务费（是联盟扣的，不要误会哦[微笑][微笑]）\n  用过联盟的都知道佣金是20号结算，我给你们21号算好发给你们\n'
                            writetxt("vip无券有佣金回复---:",msg['User']['NickName'], rebackmsg)
                            fageichaxunren(rebackmsg, msg['FromUserName'])  # 发送信息给XXXX人
                            # fageichaxunren(warning, msg['FromUserName'])  # 发送信息给XXXX人

                        else:
                            print('有券有佣金')
                            rebackmsg = '钻石用户【%s】 您好\n\n【%s】\n [口令]%s\n  [西瓜][原价] %s\n  [西瓜][优惠券] %s\n  [西瓜][现价] %s\n[太阳][太阳]如果买了预计结算的[红包]大约为：%s 元\n' % \
                                        (msg['User']['NickName'], tkl.item_name, tkl.item_tkl, tkl.item_price,
                                         tkl.item_youhuiquan, '%.2f'%(float(tkl.item_quanhouprice)), tkl.item_fanli)
                            # warning = '友好提醒---佣金默认为高级，查询的扣除10%的阿里服务费（是联盟扣的，不要误会哦[微笑][微笑]）\n  用过联盟的都知道佣金是20号结算，我给你们21号算好发给你们\n'
                            writetxt("vip有券有佣金回复---:",msg['User']['NickName'], rebackmsg)
                            fageichaxunren(rebackmsg, msg['FromUserName'])  # 发送信息给XXXX人
                            # fageichaxunren(warning, msg['FromUserName'])  # 发送信息给XXXX人
            else:
                writetxt("vip用户扔掉的过滤消息---:",msg['User']['NickName'], msg['Text'])
                print('vip用户扔掉的过滤消息-------%s'% msg['Text'])
                # 输入的无法识别，返回错误
                # fageichaxunren(msg['User']['NickName']+'，\n和你聊天可真能学到东西,你太有智慧了[微笑]', msg['FromUserName'])  # 发送信息给XXXX人
            print('这个是贵客')
    elif (re.findall('手淘',msg['Text']))or(re.findall('喵口令',msg['Text'])):    #msg['Text']就是平常的消息列表  silu匹配到查询用户的淘宝内容后要记录这个人。在改变焦点之后制造发送函数发送回去
        history.append(msg['FromUserName'])      #存一下发消息人的ID到队列
        print(real_time(),'匹配成功(手淘  喵口令)',msg['FromUserName'])
        # print(history)    #看看id存进去没有
        fageijiqiren(msg['Text'])           #发给机器人查询
    elif (re.findall('复制这条信息',msg['Text'])and(re.findall('后打开',msg['Text']))and(re.findall('淘宝',msg['Text']))):
        print(real_time(),'匹配成功(复制这条信息  后打开 淘宝)',msg['FromUserName'])
        history.append(msg['FromUserName'])      #存一下发消息人的ID到队列
        fageijiqiren(msg['Text'])           #发给机器人查
    elif (re.findall('描述',msg['Text'])and(re.findall('后',msg['Text']))and(re.findall('淘',msg['Text']))):
        print(real_time(),'匹配成功(描述  后)',msg['FromUserName'])
        history.append(msg['FromUserName'])      #存一下发消息人的ID到队列
        fageijiqiren(msg['Text'])           #发给机器人查
    elif (re.findall('制',msg['Text'])and(re.findall('后到',msg['Text']))):
        print(real_time(),'匹配成功(制  后到)',msg['FromUserName'])
        history.append(msg['FromUserName'])      #存一下发消息人的ID到队列
        fageijiqiren(msg['Text'])           #发给机器人查
    #查询日志口令
    elif re.findall('查询日志',msg['Text']):
        getlog()
    #清除日志
    elif re.findall('清空日志',msg['Text']):
        clearlog()
    elif re.findall(fanli1,msg['Text']):    #通过自动回复，再利用itchat的响应机制自动抓取（20xxxZ）对话机器人返回的红包信息，抓到的话进入下一步
        # print(history)
        if len(history)==0:      #如果==0的话说明队列没东西，需要USERID赋值避免后续错误
            UserId=""
        else:
            UserId=history.popleft()    #队列弹出左边的一个，然后赋给发消息人的标志 UserId

        fageichaxunren(tihuanneirong(msg['Text']) + '[红包][红包]' + panduanduoshaoqian(
                float(re.findall(fanli2, re.findall(fanli1, msg['Text'])[0])[0])), UserId)  # 发送红包信息给XXXX人
    elif re.findall(fanli3,msg['Text']):
        if len(history)==0:
            UserId=""
        else:
            UserId=history.popleft()
        fageichaxunren(msg['Text'],UserId)      #发送红包信息给XXXX人
    else:
        try:
            writetxt("丢弃信息---:", msg['User']['NickName'], msg['Text'])
            print(real_time(),'丢弃信息---:',msg['Text'])
        except:
            pass
#发送信息到淘宝优惠机器人号
def fageijiqiren(a):
    itchat.get_friends(update=True)#现更新号上的字典，然后下一步查找想要发送的人
    author = itchat.search_friends(name='发卡机器人')[0]
    author.send(a)
def fageichaxunren(s,e):
    itchat.get_friends(update=True)#现更新号上的字典，然后下一步查找想要发送的人
    itchat.send(s, toUserName=e)    # itchat.send_msg('已经收到了文本消息，消息内容为%s'%msg['Text'],toUserName=msg['FromUserName'])
# itchat.auto_login(enableCmdQR=True)

itchat.run()









